<template>
  <erp-modal
    :visible="visible"
    :title="title"
    width="80%"
    height="70%"
    @close="$emit('close')"
  >
    <template #default>
      <div class="staff-select">
        <div class="selected-box">
          <div class="selected-box-header">
            已选项（{{ selectedLength }}/{{ maxSelect }}）
          </div>
          <ul class="selected-ul">
            <li
              v-for="(item, index) in selectedList"
              :key="item.value"
              class="selected-li"
            >
              <div class="name">
                {{ item.label }}
              </div>
              <div class="icon">
                <i
                  class="el-icon-delete pointer"
                  @click="removeSelected(index, item)"
                />
              </div>
            </li>
          </ul>
        </div>
        <div class="tree-box">
          <div class="tree-box-header">
            <el-input
              v-model="keyword"
              placeholder="关键字搜索"
              :style="{width: '200px'}"
              suffix-icon="el-icon-search"
              clearable
              @keyup.native="searchEvent"
              @clear="searchEvent"
            />
          </div>
          <div
            v-loading="loading"
            class="tree-table"
            :element-loading-spinner="$store.state.loading.spinner"
            :element-loading-text="$store.state.loading.text"
            :element-loading-background="$store.state.loading.background"
          >
            <erp-table
              ref="tree"
              :list-permission="true"
              :show-header="false"
              :tree-config="treeConfigCom"
              :is-tree="true"
              :radio-config="radioConfigCom"
              :checkbox-config="checkboxConfigCom"
              height="100%"
              row-id="id"
              @radio-change="handleRadioChange"
              @checkbox-change="handleCheckboxChange"
            >
              <vxe-table-column
                :tree-node="true"
                field="name"
                :type="multiple ? 'checkbox' : 'radio'"
              >
                <template #default="{ row }">
                  <span style="margin-left: 10px">
                    <i class="el-icon-user-solid" />
                    <span> {{ row.name }}</span>
                  </span>
                </template>
              </vxe-table-column>
            </erp-table>
          </div>
        </div>
      </div>
    </template>
    <template #footer>
      <el-button
        type="primary"
        @click="handleSave"
      >
        确定
      </el-button>
    </template>
  </erp-modal>
</template>

<script>
import ErpModal from '@/components/erp/ErpModal/ErpModal';
import ErpTable from '@/components/erp/ErpPageTable/ErpTable';
import {base as request} from '@/request';
import {getItemFromTreeById, getRoleTree} from "./configs";
import {cloneJson, toString} from "@/utils";
import XEUtils from 'xe-utils';
/**
 * 用于角色选择
 * @author maolin
 */
export default {
  name: "RoleSelect",
  components: {
    ErpModal,
    ErpTable
  },
  props: {
    /**
     * 是否可见
     * @public
     */
    visible: {
      type: Boolean,
      default: false
    },
    /**
     * 弹窗标题
     * @public
     */
    title: {
      type: String,
      default: '角色选择'
    },
    /**
     * 是否多选模式
     * @public
     */
    multiple: {
      type: Boolean,
      default: false
    },
    /**
     * 字段名称
     * @public
     */
    label: {
      type: String,
      default: ''
    },
    /**
     * 选择的默认值
     * @public
     */
    value: {
      type: [String, Array],
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      keyword: null,
      selectedList: [],
      treeData: [],
      tableData: [],
      result: {
        label: '',
        value: ''
      }
    };
  },
  computed: {
    maxSelect () {
      return this.multiple ? 99 : 1;
    },
    selectedLength () {
      return this.selectedList && this.selectedList.length > 0 ? this.selectedList.length : 0;
    },
    treeConfigCom () {
      return {
        children: 'childs',
        defaultExpandAll: true
      };
    },
    radioConfigCom () {
      if (this.multiple) {
        return {};
      }
      let row = {};
      row = getItemFromTreeById(this.result.value, this.treeData, 'roleId');
      return  {
        reserve: false,
        labelField: 'name',
        trigger: 'row',
        highlight: true,
        checkRowKey: row ? row.id : null,
      };
    },
    checkboxConfigCom () {
      if (!this.multiple) {
        return {};
      }
      let value = this.result.value;
      let checkRowKey = [];
      let valueArray = value ? value.split(',') : [];
      let tree = cloneJson(this.treeData);
      for (let i in valueArray) {
        let row = getItemFromTreeById(valueArray[i], tree, 'roleId');
        if (row && row.id) {
          checkRowKey.push(row.id);
        }
      }
      return {
        reserve: false,
        labelField: 'name',
        trigger: 'row',
        highlight: true,
        checkStrictly: true,
        checkRowKeys: checkRowKey,
      };
    },
  },
  watch: {
    visible: {
      handler (visible, oldVisible) {
        if (visible && oldVisible !== visible) {
          this.fetchRoleList();
          this.keyword = null;
          this.result = {
            value: this.value,
            label: this.label
          };
          this.generateSelectedList();
        }
      },
      immediate: true
    },
    // result: {
    //     deep: true,
    //     handler (value, oldValue) {
    //         this.generateSelectedList()
    //     },
    //     immediate: true
    // },
    selectedList: {
      handler (list) {
        let result = {label: '', value: ''};
        let labelArray = [];
        let valueArray = [];
        if (list && list.length > 0) {
          list.map((item) => {
            labelArray.push(item.label);
            valueArray.push(item.value);
          });
        }
        result.label = labelArray.join(',');
        result.value = valueArray.join(',');
        this.result = result;
      },
      deep: true

    }
  },
  created() {
  },
  mounted() {
  },
  methods: {

    /**
     * 移除以选项
     * @param {number} index 数组索引
     * @param {object} item 已选项对象
     * @public
     */
    removeSelected (index, item) {
      this.selectedList.splice(index, 1);
      this.$nextTick(() => {
        if (!this.multiple) {
          this.$refs.tree.$refs.erpTable.clearRadioRow();
        } else {
          let value = item.value;
          let row = getItemFromTreeById(value, this.treeData, 'roleId');
          this.$refs.tree.$refs.erpTable.setCheckboxRow([row], false);
        }
      });
    },
    /**
     * 获取角色列表
     * @public
     */
    async fetchRoleList () {
      this.loading = true;
      // 获取组织架构树与人员
      this.treeData = await getRoleTree();
      this.$nextTick(() => {
        this.$refs.tree.$refs.erpTable.reloadData(this.treeData);
        this.loading = false;
      });

    },
    /**
     * 单选
     * @param {object} row 行数据对象
     * @public
     */
    handleRadioChange ({row}) {
      if (row.roleId) {
        this.selectedList = [
          {label: row.name, value: row.roleId}
        ];
      }
    },
    /**
     * 复选
     * @param {object} row 行数据对象
     * @param {boolean} checked 是否选中
     * @public
     */
    handleCheckboxChange ({row, checked}) {
      if (checked) {
        this.selectedList.push({
          label: row.name,
          value: row.roleId
        });
      } else {
        this.selectedList = this.selectedList.filter(item => item.value != row.roleId);
      }
    },
    handleSave () {
      this.$emit('value-change', this.result);
      this.$emit('close');
    },
    generateSelectedList () {
      let result = this.result;
      let value = result.value;
      let label = result.label;
      let valueArray = value ? toString(value).split(',') : [];
      let labelArray = label ? label.split(',') : [];
      let len = 0;
      let selectedList = [];
      if (valueArray.length !== labelArray.length) {
        len = Math.min(valueArray.length, labelArray.length);
      }else {
        len = valueArray.length;
      }
      if (len > 0) {
        for (let i = 0; i < len; i ++) {
          selectedList.push({
            label: labelArray[i],
            value: valueArray[i]
          });
        }
      }
      this.selectedList = selectedList;
    },
    searchEvent: XEUtils.debounce(function () {
      this.handleSearch();
    }, 500, { leading: false, trailing: true }),
    handleSearch () {
      this.loading = true;
      let filterName = toString(this.keyword) ? toString(this.keyword).trim() : '';
      if (filterName) {
        let options = { children: 'childs' };
        let searchProps = ['name'];
        this.tableData = XEUtils.searchTree(this.treeData, item => searchProps.some(key => toString(item[key]) ? toString(item[key]).indexOf(filterName) > -1 : false), options);
      } else {
        this.tableData = this.treeData;
      }
      this.$nextTick(() => {
        this.$refs.tree.$refs.erpTable.reloadData(this.tableData);
        this.loading = false;
      });
    }
  },
};
</script>

<style lang="scss" scoped>
    $primaryColor: var(--primary-color);
.staff-select{
    margin: 0;
    padding: 10px;
    display: flex;
    flex-wrap: nowrap;
    align-items: stretch;
    justify-content: space-between;
    height: 100%;
    .selected-box {
        width: calc(50% - 15px);
        margin-right: 15px;
        .selected-box-header{
            height: 40px;
            line-height: 40px;
            font-weight: bold;
            font-size: 16px;
        }
        .selected-ul{
            box-shadow: 0 0 3px #ccc;
            border: 1px solid #ccc;
            list-style: none;
            height: calc(100% - 40px);
            padding: 0;
            margin: 0;
            overflow-y: auto;
            .selected-li{
                height: 32px;
                line-height: 32px;
                padding: 0 10px;
                display: flex;
                flex-wrap: nowrap;
                &:hover{
                    background-color: #F5F7FA;
                }
                .name{
                    width: calc(100% - 30px);
                }
                .icon{
                    width: 30px;
                    text-align: right;
                    i{
                        font-size: 16px;
                    }
                }
            }
        }
    }
    .tree-box{
        width: 50%;
        .tree-box-header{
            height: 40px;
            line-height: 40px;
            font-weight: bold;
            font-size: 16px;
        }
        .tree-table{
            height: calc(100% - 40px);
            ::v-deep{
                .vxe-table--render-default .is--disabled.vxe-cell--radio,.vxe-table--render-default .is--disabled.vxe-cell--checkbox{
                    color: #333;
                }
                .vxe-table--render-default .vxe-body--column.col--ellipsis>.vxe-cell .vxe-tree-cell .vxe-cell--radio.is--disabled{
                    padding-left: 0;
                    .vxe-radio--icon.vxe-radio--unchecked-icon{
                        display: none;
                    }
                }
                .vxe-table--render-default .vxe-body--column.col--ellipsis>.vxe-cell .vxe-tree-cell .vxe-cell--checkbox.is--disabled{
                    padding-left: 0;
                    .vxe-checkbox--icon.vxe-checkbox--unchecked-icon{
                        display: none;
                    }
                }
            }
        }
    }
}
</style>
